<template>
  <el-card class="box-card">
    <!--添加按钮-->
    <el-button type="primary" icon="plus" @click="addTrademark(ruleFormRef)">
      添加品牌
    </el-button>
    <!--表格组件-->
    <el-table
      border
      style="width: 100%; margin: 10px 0px"
      :data="trademarkList"
    >
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <template #="{ row, column, $index }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, column, $index }">
          <el-button
            type="primary"
            icon="edit"
            size="small"
            @click="editTrademark(row, ruleFormRef)"
          />
          <el-popconfirm
            :title="`你是否要删除品牌${row.tmName}?`"
            width="250px"
            icon="delete"
            @confirm="deleteTrademark(row.id)"
          >
            <template #reference>
              <el-button type="primary" icon="delete" size="small" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--
      Pagination 分页
        v-model:current-page: 当前页数
        v-model:page-size: 每页显示条目个数
        background: 是否为分页按钮添加背景色
        page-sizes: 每页显示个数选择器的选项设置
        layout: 组件布局，子组件名用逗号分隔
    -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      background
      layout="prev, pager, next, jumper, ->, sizes, total,"
      :total="total"
      @size-change="sizeChange"
      @current-change="getTrademarkList"
    />
  </el-card>
  <!--对话框组件-->
  <el-dialog
    v-model="dialogVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    width="40%"
  >
    <el-form ref="ruleFormRef" :model="trademarkParams" :rules="rules">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          v-model="trademarkParams.tmName"
          placeholder="请输入品牌名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="Confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'

import {
  TrademarkGetPageList,
  AddOrUpdateTrademark,
  DeleteTrademark,
} from '@/api/product/trademark'

import { ElMessage } from 'element-plus'

import type { UploadProps } from 'element-plus'

import type {
  TrademarkResponsePageData,
  Records,
  Trademark,
} from '@/api/product/trademark/type'
///引入自定义验证规则
import type { FormInstance, FormRules } from 'element-plus'
//验证表单模型
const ruleFormRef = ref<FormInstance>()
//名称验证规则
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.length <= 2) {
    callback(new Error('品牌名称长度不能小于3'))
  } else {
    callback()
  }
}
const validateLogo = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('图片不能为空'))
  }
}

//自定义验证规则集合
const rules = reactive<FormRules<typeof trademarkParams>>({
  tmName: [{ validator: validateTmName, trigger: 'blur', required: true }],
  logoUrl: [{ validator: validateLogo, required: true }],
})

let currentPage = ref<number>(1)

let pageSize = ref<number>(3)

let total = ref<number>(0)

const trademarkList = ref<Records>([])
//设置对话框组件的显示与隐藏
let dialogVisible = ref<boolean>(false)
//添加数据页面
const addTrademark = (formEl: FormInstance | undefined) => {
  dialogVisible.value = true
  trademarkParams.id = 0
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
  //删除错误信息
  if (!formEl) return
  formEl.resetFields()
}
//修改数据
const editTrademark = (row: Trademark, formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = true
  Object.assign(trademarkParams, row)
}

//删除品牌信息
const deleteTrademark = async (id: number) => {
  let result = await DeleteTrademark(id)
  if (result.code == 200) {
    ElMessage.success('删除成功！')
    //重新获取列表
    getTrademarkList(
      trademarkList.value.length > 1
        ? currentPage.value
        : currentPage.value - 1,
    )
  } else {
    ElMessage.error(result.message)
  }
}

const trademarkParams: Trademark = reactive({
  tmName: '',
  logoUrl: '',
})

//确定按钮事件回调
const Confirm = async () => {
  //发送请求前先验证
  await ruleFormRef.value?.validate()
  let result: any = await AddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    ElMessage.success(`品牌${result.id ? '修改' : '添加'}成功！`)
    sizeChange(result.id ? 1 : currentPage.value)
  } else {
    ElMessage.success(`品牌${result.id ? '修改' : '添加'}失败！`)
  }
  dialogVisible.value = false
}

//取消按钮事件回调
const Cancel = () => {
  dialogVisible.value = false
}

//获取品牌信息列表
const getTrademarkList = async () => {
  let result: TrademarkResponsePageData = await TrademarkGetPageList(
    currentPage.value,
    pageSize.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    trademarkList.value = result.data.records
  }
}

//文件上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data
}
//文件上传开始前回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只能上传jpeg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('图片大小最大为4MB!')
    return false
  }
  return true
}

onMounted(() => {
  getTrademarkList()
})

const sizeChange = (pager = 1) => {
  currentPage.value = pager
  getTrademarkList()
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
